package com.newgd.blockchain.demo.task;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.newgd.blockchain.demo.util.HttpRequestUtil;
import com.newgd.blockchain.demo.util.RequestResult;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by Niki on 2018/4/14 10:08
 */
public class TradesRequest {
    private static final Logger LOGGER = LoggerFactory.getLogger(TradesRequest.class);
    private static Integer lastTID;
    private static String url = "https://localbitcoins.com/bitcoincharts/cny/trades.json";
    private static Map<String, Object> params = Maps.newHashMap();

    public static JSONArray getTrades() {
        if (!StringUtils.isEmpty(lastTID)) {
            params.put("last", lastTID);
        }
        RequestResult result = null;
        try {
            result = HttpRequestUtil.doGet( url,params);

        } catch (Exception e) {
            LOGGER.error("【查询交易数据】出错！last is {}", lastTID, e);
        }
        if (result != null && result.getStatusCode() == HttpStatus.SC_ACCEPTED) {
            try {
                JSONArray data = JSONArray.parseArray(result.getMessage());
                lastTID = data.getJSONObject(data.size() - 1).getInteger("tid");
                return data;
            } catch (Exception e) {
                LOGGER.error("【查询交易数据】{}后转JSONARRAY出错！", result, e);
            }
        }
        return null;
    }

}
